<?php
/**
 * Note: *
 * Date: 2021/8/06
 */
namespace App\Caches;

use Illuminate\Support\Facades\Cache;

class RealNameCache
{
    public const CACHE_TAG = 'real-name';

    public const KEY_LOGIN = 'login';
    public const KEY_LOGOUT = 'logout';

    /**
     * 重置缓存
     */
    public static function reset()
    {
        Cache::tags(self::CACHE_TAG)->flush();
    }

    /**
     * 记录上线用户
     * @param int $userId
     */
    public static function setLogin(int $userId)
    {
        $collect = Cache::tags(self::CACHE_TAG)->get(self::KEY_LOGIN);
        if (!$collect) $collect = collect([]);

        Cache::tags(self::CACHE_TAG)->put(self::KEY_LOGIN, $collect->add([
            'user_id' => $userId,
            'time' => now()->timestamp,
        ]), 600);
    }

    /**
     * 记录下线用户
     * @param int $userId
     */
    public static function setLogout(int $userId)
    {
        $collect = Cache::tags(self::CACHE_TAG)->get(self::KEY_LOGOUT);
        if (!$collect) $collect = collect([]);

        Cache::tags(self::CACHE_TAG)->put(self::KEY_LOGOUT, $collect->add([
            'user_id' => $userId,
            'time' => now()->timestamp,
        ]), 600);
    }

    /**
     * @return \Illuminate\Support\Collection|mixed
     */
    public static function getLogin()
    {
        return Cache::tags(self::CACHE_TAG)->pull(self::KEY_LOGIN) ?: collect();
    }

    /**
     * @return \Illuminate\Support\Collection|mixed
     */
    public static function getLogout()
    {
        return Cache::tags(self::CACHE_TAG)->pull(self::KEY_LOGOUT) ?: collect();
    }
}
